package com.woniuxy.tfss.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.tfss.entity.Discount;
import com.woniuxy.tfss.entity.DiscountVO;
import com.woniuxy.tfss.entity.Rider;
import com.woniuxy.tfss.entity.User;
import com.woniuxy.tfss.exception.NoAccountException;
import com.woniuxy.tfss.exception.PasswordWrongException;
import com.woniuxy.tfss.mapper.UserMapper;
import com.woniuxy.tfss.service.DiscountService;
import com.woniuxy.tfss.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired
    private DiscountService discountService;

    @Override
    public User getUserByPhoneNum(String phoneNum) {
        return userMapper.getUserByPhoneNum(phoneNum);
    }

    @Override
    public User login(String phoneNum, String password) {
        //String status = userMapper.getStatusByNum(phoneNum);
        QueryWrapper<User> userQueryWrapper1 = new QueryWrapper<>();
        userQueryWrapper1.eq("phonenum",phoneNum);
        userQueryWrapper1.eq("status",'1');

        QueryWrapper<User> userQueryWrapper2 = new QueryWrapper<>();
        userQueryWrapper2.eq("phonenum",phoneNum);
        userQueryWrapper2.eq("password",password);

        if(userMapper.selectCount(userQueryWrapper1) == 0){
            throw new NoAccountException("账号不存在或被禁用！");
        }else{
            if (userMapper.selectCount(userQueryWrapper2) == 0){
                throw new PasswordWrongException("密码错误！");
            }else{
                return userMapper.selectOne(userQueryWrapper2);
            }
        }
    }

    @Override
    public List<Discount> getDiscountsByUserId(Integer userId) {
        return userMapper.getDiscountsByUserId(userId);
    }

    @Override
    public void addDiscount(Integer userId, Integer discountId, String time) throws ParseException {
        Discount discount=discountService.getById(discountId);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = df.parse(time);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.DATE, discount.getExpiryDate());
        userMapper.addDiscount(userId,discountId,df.format(calendar.getTime()));
    }

    //使用优惠券后删除对应
    @Override
    public void reduceDiscount(Integer userId, Integer discountId) {
        userMapper.reduceDiscount(userId, discountId);
    }

}
